package database

import (
	"database/sql"
	"github.com/gogf/gf/frame/g"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"time"
)

var sqlDb *sql.DB
var conn *gorm.DB

func connect() {
	//var cstZone = time.FixedZone("CST", 8*3600) // 东八
	//time.Local = cstZone
	//time.LoadLocation("Asia/Shanghai")
	config := g.Cfg()

	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	var connectErr error
	conn, connectErr = gorm.Open(mysql.New(mysql.Config{
		DSN:                       config.GetString("database.dsn"), // DSN data source name
		DefaultStringSize:         255,                              // string 类型字段的默认长度
		DisableDatetimePrecision:  true,
		SkipInitializeWithVersion: false,
	}), &gorm.Config{
		SkipDefaultTransaction:   true, // 跳过默认事务
		DisableNestedTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
	})
	if connectErr != nil {
		panic(connectErr)
	}
	sqlDb, _ = conn.DB()
	sqlDb.SetMaxIdleConns(10)
	sqlDb.SetMaxOpenConns(100)
	sqlDb.SetConnMaxLifetime(time.Hour)
}

func SqlDb() *sql.DB {
	if sqlDb == nil {
		connect()
	}
	return sqlDb
}

func Db() *gorm.DB {
	if sqlDb == nil {
		connect()
	}
	return conn
}
